/**
 * <copyright>
 *
 * Copyright (c) 2002-2006 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: 
 *   IBM - Initial API and implementation
 *
 * </copyright>
 *
 * $Id: NotificationChainImpl.java,v 1.4 2007/06/12 20:56:17 emerks Exp $
 */
package org.oppoweb.emf.common.notify.classes {


import org.oppoweb.emf.common.notify.Notification;
import org.oppoweb.emf.common.notify.NotificationChain;
import org.oppoweb.emf.common.notify.Notifier;
import org.oppoweb.emf.common.util.BasicEList;

/**
 * A list that acts as a notification chain.
 */
public class NotificationChainImpl extends BasicEList implements NotificationChain
{
  /**
   * Creates an empty instance.
   */
  public NotificationChainImpl()
  {
    super();
  }

  /**
   * Creates an empty instance with a given capacity.
   * @param initialCapacity the initial capacity of the list before it must grow.
   */
  public NotificationChainImpl(int initialCapacity)
  {
    super(initialCapacity);
  }

  /**
   * Returns new data storage of type {@link Notification}[].
   * @return new data storage.
   */
  protected  function newData(capacity:int):Object []
  {
    return new Notification[capacity];
  }

  /**
   * Adds or merges a new notification.
   * @param newNotification a notification.
   * @return <code>true</code> when the notification is added and <code>false</code> when it is merged.
   */
  @Override
  public function add(newNotification:Notification):Boolean
  {
    if (newNotification == null)
    {
      return false;
    }
    else 
    {
      for (int i = 0; i < size; i++)
      {
        var notification:Notification = data[i] as Notification;
        if (notification.merge(newNotification))
        {
          return false;
        }
      }

      return super.push(newNotification);
    }
  }

  public function dispatch():void
  {
    for (int i = 0; i < size; i++)
    {
      var notification:Notification = data[i] as Notification;
      dispatch(notification);
    }
  }

  /**
   * Dispatches the notification to its notifier.
   */
  protected function dispatch(notification:Notification):void
  {
    var notifier:Object = notification.getNotifier();
    if (notifier != null && notification.getEventType() != -1)
    {
      (notifier as Notifier).eNotify(notification);
    }
  }
}
}